package com.ruoyi.web.controller.work;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.integrate.constant.WxConstant;
import com.ruoyi.common.integrate.service.QYWeiXinService;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.framework.web.service.SysLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.httpclient.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Objects;

/**
 * @Author: MMDZ
 * @Desc: TODO 企业微信OAuth2验证
 */
@Controller
@RequestMapping("/wx")
public class WorkAppController extends BaseController {

    @Autowired
    private QYWeiXinService qyWeiXinService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private SysLoginService loginService;
    @Autowired
    private TokenService tokenService;
    @Value("${qyweixin.corpid}")
    private String corpid;//企业id

    // 测试 http://localhost:8077/wx/test
    @GetMapping("/test")
    public String test(HttpServletRequest request) {
        String userId = "CN802327";
        SysUser user = sysUserService.selectUserByUserName(userId);
        if (Objects.isNull(user)) throw new ServiceException("获取用户信息异常，请联系管理员", HttpStatus.SC_INTERNAL_SERVER_ERROR);

        // 获取用户id
        Long sysUserId = null;
        // 获取部门
        String dept = null;
        // 获取用户名
        String nickname = null;
        try {
            sysUserId = user.getUserId();
            // 解决redirect参数中文乱码问题(指定的编码格式进行编码)
            nickname = URLEncoder.encode(user.getNickName(), "utf-8");
            dept = URLEncoder.encode(user.getDept().getDeptName(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 获取token
        String token = "123456789";
        // 免密登录-获取token
        LoginUser loginUser = tokenService.getLoginUser(request);
        logger.info("loginUser = " + loginUser);
        if (Objects.isNull(loginUser)) {
            String cleartext = sysUserService.getCleartextPassword(userId);// 获取明文的密码（不能使用加密的密码，否则验证不通过）
            token = loginService.login(userId, cleartext);
        }

        // 重定向路径(重定向到app页面)
        String redirectUrl = String.format("http://localhost:8099/workApp?userid=%s&username=%s&nickname=%s&dept=%s&token=%s", sysUserId, userId, nickname, dept, token);
        logger.info("redirectUrl = " + redirectUrl);
        return redirect(redirectUrl);
    }

    /**
     * 填报
     *
     * @param request
     * @return
     */
    @GetMapping("/oauth2wx.do")
    public String workApp(HttpServletRequest request) {
        logger.info("进入企业微信页面自定义方法。。。。。。");

        //获取项目域名
        String requestUrl = request.getRequestURL().toString();
        requestUrl = requestUrl.substring(0, requestUrl.lastIndexOf("/"));

        //拼接微信回调地址
        String backUrl = requestUrl + "/oauth2me.do";
        String redirect_uri = "";
        logger.info("backUrl = " + backUrl);

        try {
            redirect_uri = HttpUtils.urlEncodeURL(backUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("eCode error: " + e.getMessage());
        }
        // 拼接企业微信网页授权地址
        String oauth2Url = String.format(WxConstant.WX_CONNECT_OAUTH2_AUTHORIZE_URL, corpid, redirect_uri);
        return redirect(oauth2Url);
    }

    /**
     * 填报-授权回调请求处理
     *
     * @return
     */
    @GetMapping("/oauth2me.do")
    public String oAuth2Url(HttpServletRequest request, @RequestParam String code) {
        // 获取访问用户身份 --- 根据code获取成员信息 UserId
        String userId = qyWeiXinService.getUserInfoByCode(code);
        SysUser user = sysUserService.selectUserByUserName(userId);
        if (Objects.isNull(user)) throw new ServiceException("获取用户信息异常，请联系管理员", HttpStatus.SC_INTERNAL_SERVER_ERROR);

        // 获取用户id
        Long sysUserId = null;
        // 获取部门
        String dept = null;
        // 获取用户名
        String nickname = null;
        try {
            sysUserId = user.getUserId();
            // 解决redirect参数中文乱码问题(指定的编码格式进行编码)
            nickname = URLEncoder.encode(user.getNickName(), "utf-8");
            dept = URLEncoder.encode(user.getDept().getDeptName(), "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 获取token
        String token = "123456789";
        // 免密登录-获取token
        LoginUser loginUser = tokenService.getLoginUser(request);
        logger.info("loginUser = " + loginUser);
        if (Objects.isNull(loginUser)) {
            String cleartext = sysUserService.getCleartextPassword(userId);// 获取明文的密码（不能使用加密的密码，否则验证不通过）
            token = loginService.login(userId, cleartext);
        }

        // 重定向路径(重定向到app页面)
        String redirectUrl = String.format("http://oa.cannice.hk:8099/workApp?userid=%s&username=%s&nickname=%s&dept=%s&token=%s", sysUserId, userId, nickname, dept, token);
        logger.info("redirectUrl = " + redirectUrl);
        return redirect(redirectUrl);
    }

    /** ---------------------------------------------------------------------------------------------- */

    /**
     * 审核
     *
     * @param request
     * @return
     */
    @GetMapping("/oauth2wx.check")
    public String workAppCheck(HttpServletRequest request) {
        logger.info("进入企业微信页面自定义方法-----审核");

        //获取项目域名
        String requestUrl = request.getRequestURL().toString();
        requestUrl = requestUrl.substring(0, requestUrl.lastIndexOf("/"));

        //拼接微信回调地址
        String backUrl = requestUrl + "/oauth2me.check";
        String redirect_uri = "";
        logger.info("backUrl = " + backUrl);

        try {
            redirect_uri = HttpUtils.urlEncodeURL(backUrl);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("eCode error: " + e.getMessage());
        }
        // 拼接企业微信网页授权地址
        String oauth2Url = String.format(WxConstant.WX_CONNECT_OAUTH2_AUTHORIZE_URL, corpid, redirect_uri);
        return redirect(oauth2Url);
    }

    /**
     * 审核-授权回调请求处理
     *
     * @return
     */
    @GetMapping("/oauth2me.check")
    public String oAuth2UrlCheck(HttpServletRequest request, @RequestParam String code) {
        // 获取访问用户身份 --- 根据code获取成员信息 UserId
        String userId = qyWeiXinService.getUserInfoByCode(code);
        SysUser user = sysUserService.selectUserByUserName(userId);
        if (Objects.isNull(user)) throw new ServiceException("获取用户信息异常，请联系管理员", HttpStatus.SC_INTERNAL_SERVER_ERROR);

        // 获取token
        String token = "123456789";
        // 免密登录-获取token
        LoginUser loginUser = tokenService.getLoginUser(request);
        logger.info("loginUser = " + loginUser);
        if (Objects.isNull(loginUser)) {
            String cleartext = sysUserService.getCleartextPassword(userId);// 获取明文的密码（不能使用加密的密码，否则验证不通过）
            token = loginService.login(userId, cleartext);
        }

        // 重定向路径(重定向到app页面)
        String redirectUrl = String.format("http://oa.cannice.hk:8099/workAppCheck?token=%s", token);
        logger.info("redirectUrl = " + redirectUrl);
        return redirect(redirectUrl);
    }

}
